package com.mission.schedule.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.R;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.RepeatBean;
import com.mission.schedule.bean.WBA_FindFunctionMy;
import com.mission.schedule.clock.RepeatDateUtil;
import com.mission.schedule.constants.Const;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.widget.MyGridView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class RecommendActivity extends Activity {

    SharedPrefUtil sharedPrefUtil;
    ProgressUtil progressUtil;
    List<List<WBA_FindFunctionMy.ListBean>> lists = new ArrayList<>();
    ExpandableListView expand_listview;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.repeat_xiaochengxun);
        findViewById(R.id.top_ll_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        sharedPrefUtil = new SharedPrefUtil(getApplication(), ShareFile.USERFILE);
        progressUtil = new ProgressUtil();

        lists.add(App.getDBcApplication().getAll_tb_function_my(1));
        lists.add(App.getDBcApplication().getAll_tb_function_my(2));
        lists.add(App.getDBcApplication().getAll_tb_function_my(3));
//        lists.add(App.getDBcApplication().getAll_tb_function_my(4, 6));

        expand_listview = findViewById(R.id.expand_listview);
        expand_listview.setGroupIndicator(null);
        Adapter adapter = new Adapter();
        expand_listview.setAdapter(adapter);

        int groupCount = expand_listview.getCount();
        for (int i = 0; i < groupCount; i++) {
            expand_listview.expandGroup(i);
        }

        expand_listview.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                v.setClickable(true);
                return true;
            }
        });

        if (lists.size() == 0) {
            downdata();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void downdata() {
        progressUtil.ShowProgress(this, true, true, "正在下载");
        RequestParams params1 = new RequestParams();
        params1.addBodyParameter("changTime", sharedPrefUtil.getString(ShareFile.tb_function_my, ""));
        new HttpUtils(5000).send(HttpMethod.POST, URLConstants.小程序表, params1, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    try {
                        Gson gson = new Gson();
                        WBA_FindFunctionMy bean = gson.fromJson(responseInfo.result, WBA_FindFunctionMy.class);
                        if (bean.status == 0) {
                            sharedPrefUtil.putString(getApplicationContext(), ShareFile.USERFILE, ShareFile.tb_function_my, bean.downTime.replace('T', ' '));
                            List<WBA_FindFunctionMy.ListBean> list = bean.list;

                            if (list != null) {
                                for (WBA_FindFunctionMy.ListBean listBean : list) {
                                    App.getDBcApplication().insert_tb_function_my(listBean);
                                }
                            }
                        }
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                    }
                }
                progressUtil.dismiss();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.e("TAG", s);
                progressUtil.dismiss();
            }
        });
    }


    class Adapter extends BaseExpandableListAdapter {

        @Override
        public int getGroupCount() {
            return lists.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return 1;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return lists.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return lists.get(groupPosition).get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            GroupHolder holder;
            if (convertView == null) {
                holder = new GroupHolder();
                convertView = LayoutInflater.from(RecommendActivity.this).inflate(R.layout.repeat_zhengdian_header, parent, false);
                holder.zd_header = convertView.findViewById(R.id.zd_header);
                convertView.setTag(holder);
            } else {
                holder = (GroupHolder) convertView.getTag();
            }

            switch (groupPosition) {
                case 0:
                    holder.zd_header.setText("每天 , 工作日 , 常用");
                    break;
                case 1:
                    holder.zd_header.setText("每周");
                    break;
                case 2:
                    holder.zd_header.setText("每月");
                    break;
            }

            return convertView;
        }

        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            ChildHolder holder;
            if (convertView == null) {
                holder = new ChildHolder();
                convertView = LayoutInflater.from(RecommendActivity.this).inflate(R.layout.recom_group_gridview, parent, false);
                holder.mygridview = convertView.findViewById(R.id.mygridview);
                convertView.setTag(holder);
            } else {
                holder = (ChildHolder) convertView.getTag();
            }
            List<WBA_FindFunctionMy.ListBean> beanList = lists.get(groupPosition);
            int i = 3 - beanList.size() % 3;
            if (i == 3) i = 0;
            for (int s = 0; s < i; s ++){
                WBA_FindFunctionMy.ListBean bean = new WBA_FindFunctionMy.ListBean();
                bean.name = "";
                bean.remark1 = "1";
                beanList.add(bean);
            }
            GridAdapter gridAdapter = new GridAdapter(beanList);
            holder.mygridview.setAdapter(gridAdapter);
            holder.mygridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (!lists.get(groupPosition).get(position).name.isEmpty()) {
                        dialogPauseDetailOnClick(groupPosition, lists.get(groupPosition).get(position).remark1,lists.get(groupPosition).get(position));
                    }
                }
            });
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

        class GroupHolder {
            TextView zd_header;
        }

        class ChildHolder {
            MyGridView mygridview;
        }
    }

    class GridAdapter extends BaseAdapter {

        List<WBA_FindFunctionMy.ListBean> list = new ArrayList<>();

        public GridAdapter(List<WBA_FindFunctionMy.ListBean> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return list.get(position).id;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                holder = new Holder();
                convertView = LayoutInflater.from(RecommendActivity.this).inflate(R.layout.recom_item, parent, false);
                holder.item = convertView.findViewById(R.id.item);
                holder.xiaochengxun = convertView.findViewById(R.id.xiaochengxun);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }

            holder.item.setText(list.get(position).name);
            if (list.get(position).remark1.equals("0")) {
                holder.item.setTextColor(getResources().getColor(R.color.title0));
                holder.xiaochengxun.setVisibility(View.VISIBLE);
            }
            return convertView;
        }

        class Holder {
            TextView item, xiaochengxun;
        }
    }

    private void dialogPauseDetailOnClick(int groupPosition, String reamrk1, WBA_FindFunctionMy.ListBean bean) {
        Dialog dialog = new Dialog(this, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(this);
        View more_pop_menu = fac.inflate(R.layout.dialog_recom, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.show();

        new MyGeneralPauseDetailOnClick(dialog, more_pop_menu, groupPosition, reamrk1, bean);
    }

    class MyGeneralPauseDetailOnClick implements View.OnClickListener {

        private View view;
        private Dialog dialog;
        private TextView add1,add2,add3,open;
        private TextView cancle_tv;
        int groupPosition;
        String reamrk1;
        WBA_FindFunctionMy.ListBean bean;

        Calendar calendar = Calendar.getInstance();

        @SuppressLint("NewApi")
        public MyGeneralPauseDetailOnClick(Dialog dialog, View view,int groupPosition, String reamrk1,WBA_FindFunctionMy.ListBean bean) {
            this.dialog = dialog;
            this.view = view;
            this.groupPosition = groupPosition;
            this.reamrk1 = reamrk1;
            this.bean = bean;
            initview();
        }

        private void initview() {
            add1 = view.findViewById(R.id.add1);
            add2 = view.findViewById(R.id.add2);
            add3 = view.findViewById(R.id.add3);
            open = view.findViewById(R.id.open);
            cancle_tv = view.findViewById(R.id.cancle_tv);
            cancle_tv.setOnClickListener(this);
            add1.setOnClickListener(this);
            add2.setOnClickListener(this);
            add3.setOnClickListener(this);
            open.setOnClickListener(this);

            if (reamrk1.equals("1")) {
                open.setVisibility(View.GONE);
            }

            if (groupPosition == 1) {
                add1.setVisibility(View.GONE);
                add2.setText("加入每周重复");
            }

            if (groupPosition == 2) {
                add1.setVisibility(View.GONE);
                add2.setText("加入每月重复");
            }

        }

        @Override
        public void onClick(View v) {
            String maxTitleId;
            RepeatBean repeatBean;
            Intent intent = new Intent(Const.SHUAXINDATA);
            intent.putExtra("data", "success");
            intent.putExtra("index", 1);
            intent.putExtra("what", 2);
            switch (v.getId()) {
                case R.id.add1:
                    dialog.dismiss();
                    maxTitleId = DateUtil.nowTime2();
                    repeatBean = RepeatDateUtil.dateTimeToChildAlarmDate(
                            bean.remark1.equals("1") ? (bean.remark2.isEmpty() ? "23:59" : bean.remark2) : "23:59", 1, "", "",bean.remark2.isEmpty() ? "0" : "1");
                    App.getDBcApplication().insertCLRepeatTableData(0, 0,
                            0, 1, 1, 0, 0, 0, 1,
                            "[]", repeatBean.repNextCreatedTime,
                            repeatBean.repLastCreatedTime,
                            DateUtil.formatDateTime(new Date()),
                            repeatBean.repNextCreatedTime, bean.name,
                            DateUtil.formatDateTime(new Date()), maxTitleId, "0",
                            bean.remark1.equals("1") ? (bean.remark2.isEmpty() ? "23:59" : bean.remark2) : "23:59", "完成任务", "g_88",
                            DateUtil.formatDateTime(new Date()), 0, "", 0,
                            "", "", 0, 0, 0, "", "",
                            0, 0, "", 0, 0, "0", "","","","","","");
                    App.getDBcApplication().insertScheduleData(bean.name,
                            repeatBean.repNextCreatedTime.substring(0, 10),
                            repeatBean.repNextCreatedTime.substring(11, 16),
                            1, 0, bean.remark1.equals("1") ? 1 : 0, 0, 0, 0,
                            0, repeatBean.repNextCreatedTime, "", 0, maxTitleId, "0",
                            App.getDBcApplication().repschId, repeatBean.repNextCreatedTime,
                            DateUtil.formatDateTime(new Date()), 0, 0,
                            1, "完成任务", "g_88", "", 0, 0,
                            0, bean.url, "", 0, 0, 0, 0, "","0","0");
                    App.getDBcApplication().updateRepeatremark2(App.getDBcApplication().repschId + "",  bean.remark1.equals("1") ? "" : bean.id+"");
                    App.getDBcApplication().updateRepeatTimeNextDate(App.getDBcApplication().repschId + "", repeatBean.repNextCreatedTime);
                    Toast.makeText(RecommendActivity.this, "已添加", Toast.LENGTH_SHORT).show();
                    sendBroadcast(intent);
                    break;
                case R.id.add2:
                    dialog.dismiss();
                    if (groupPosition == 0) {//工作日
                        maxTitleId = DateUtil.nowTime2();
                        repeatBean = RepeatDateUtil.dateTimeToChildAlarmDate(
                                bean.remark1.equals("1") ? (bean.remark2.isEmpty() ? "23:59" : bean.remark2) : "23:59"
                                , 5, "", "",bean.remark2.isEmpty() ? "0" : "1");
                        App.getDBcApplication().insertCLRepeatTableData(0, 0,
                                0, 5, 1, 0, 0, 0, 1,
                                "[]", repeatBean.repNextCreatedTime,
                                repeatBean.repLastCreatedTime,
                                DateUtil.formatDateTime(new Date()),
                                repeatBean.repNextCreatedTime, bean.name,
                                DateUtil.formatDateTime(new Date()), maxTitleId, "0",
                                bean.remark1.equals("1") ? (bean.remark2.isEmpty() ? "23:59" : bean.remark2) : "23:59", "完成任务", "g_88",
                                DateUtil.formatDateTime(new Date()), 0, "", 0,
                                "", "", 0, 0, 0, "", "",
                                0, 0, "", 0, 0, "0", "","","","","","");
                        App.getDBcApplication().insertScheduleData(bean.name,
                                repeatBean.repNextCreatedTime.substring(0, 10),
                                repeatBean.repNextCreatedTime.substring(11, 16),
                                1, 0, bean.remark1.equals("1") ? 1 : 0, 0, 0, 0,
                                0, repeatBean.repNextCreatedTime, "", 0, maxTitleId, "0",
                                App.getDBcApplication().repschId, repeatBean.repNextCreatedTime,
                                DateUtil.formatDateTime(new Date()), 0, 0,
                                1, "完成任务", "g_88", "", 0, 0,
                                0, bean.url, "", 0, 0, 0, 0, "","0","0");
                        App.getDBcApplication().updateRepeatremark2(App.getDBcApplication().repschId + "",  bean.remark1.equals("1") ? "" : bean.id+"");
                        App.getDBcApplication().updateRepeatTimeNextDate(App.getDBcApplication().repschId + "", repeatBean.repNextCreatedTime);
                        Toast.makeText(RecommendActivity.this, "已添加", Toast.LENGTH_SHORT).show();

                        sendBroadcast(intent);
                    }
                    if (groupPosition == 1) {//每周
                        maxTitleId = DateUtil.nowTime2();
                        String week = bean.repTypeParameter.replace("[","").replace("]","");
                        switch (week) {
                            case "1": week = "星期一";  break;
                            case "2": week = "星期二";  break;
                            case "3": week = "星期三";  break;
                            case "4": week = "星期四";  break;
                            case "5": week = "星期五";  break;
                            case "6": week = "星期六";  break;
                            case "7": week = "星期日";  break;
                        }
                        repeatBean = RepeatDateUtil.dateTimeToChildAlarmDate("23:59", 2, week, "","0");
                        App.getDBcApplication().insertCLRepeatTableData(0, 0,
                                0, 2, 1, 0, 0, 0, 1,
                                bean.repTypeParameter, repeatBean.repNextCreatedTime,
                                repeatBean.repLastCreatedTime,
                                DateUtil.formatDateTime(new Date()),
                                repeatBean.repNextCreatedTime, bean.name,
                                DateUtil.formatDateTime(new Date()), maxTitleId, "0",
                                "23:59", "完成任务", "g_88",
                                DateUtil.formatDateTime(new Date()), 0, "", 0,
                                "", "", 0, 0, 0, "", "",
                                0, 0, "", 0, 0, "0", "","","","","","");
                        App.getDBcApplication().insertScheduleData(bean.name,
                                repeatBean.repNextCreatedTime.substring(0, 10),
                                repeatBean.repNextCreatedTime.substring(11, 16),
                                1, 0, 0, 0, 0, 0,
                                0, repeatBean.repNextCreatedTime, "", 0, maxTitleId, "0",
                                App.getDBcApplication().repschId, repeatBean.repNextCreatedTime,
                                DateUtil.formatDateTime(new Date()), 0, 0,
                                1, "完成任务", "g_88", "", 0, 0,
                                0, bean.url, "", 0, 0, 0, 0, "","0","0");
                        App.getDBcApplication().updateRepeatremark2(App.getDBcApplication().repschId + "", bean.remark1.equals("1") ? "" : bean.id+"");
                        App.getDBcApplication().updateRepeatTimeNextDate(App.getDBcApplication().repschId + "", repeatBean.repNextCreatedTime);
                        Toast.makeText(RecommendActivity.this, "已添加", Toast.LENGTH_SHORT).show();
                        sendBroadcast(intent);
                    }
                    if (groupPosition == 2) {//每月
                        maxTitleId = DateUtil.nowTime2();
                        repeatBean = RepeatDateUtil.dateTimeToChildAlarmDate("23:59", 3, bean.repTypeParameter.replace("[","").replace("]",""), "","0");
                        App.getDBcApplication().insertCLRepeatTableData(0, 0,
                                0, 3, 1, 0, 0, 0, 1,
                                bean.repTypeParameter, repeatBean.repNextCreatedTime,
                                repeatBean.repLastCreatedTime,
                                DateUtil.formatDateTime(new Date()),
                                repeatBean.repNextCreatedTime, bean.name,
                                DateUtil.formatDateTime(new Date()), maxTitleId, "0",
                                "23:59", "完成任务", "g_88",
                                DateUtil.formatDateTime(new Date()), 0, "", 0,
                                "", "", 0, 0, 0, "", "",
                                0, 0, "", 0, 0, "0", "","","","","","");
                        App.getDBcApplication().insertScheduleData(bean.name,
                                repeatBean.repNextCreatedTime.substring(0, 10),
                                repeatBean.repNextCreatedTime.substring(11, 16),
                                1, 0, 0, 0, 0, 0,
                                0, repeatBean.repNextCreatedTime, "", 0, maxTitleId, "0",
                                App.getDBcApplication().repschId, repeatBean.repNextCreatedTime,
                                DateUtil.formatDateTime(new Date()), 0, 0,
                                1, "完成任务", "g_88", "", 0, 0,
                                0, bean.url, "", 0, 0, 0, 0, "","0","0");
                        App.getDBcApplication().updateRepeatremark2(App.getDBcApplication().repschId + "", bean.remark1.equals("1") ? "" : bean.id+"");
                        App.getDBcApplication().updateRepeatTimeNextDate(App.getDBcApplication().repschId + "", repeatBean.repNextCreatedTime);
                        Toast.makeText(RecommendActivity.this, "已添加", Toast.LENGTH_SHORT).show();
                        sendBroadcast(intent);
                    }
                    break;
                case R.id.add3://schRemark6
                    dialog.dismiss();
                    maxTitleId = DateUtil.nowTime2();
                    App.getDBcApplication().insertScheduleDataremark6(bean.name,
                            DateUtil.formatDate(new Date()),
                            bean.remark1.equals("1") ? (bean.remark2.isEmpty() ? "23:59" : bean.remark2) : "23:59",
                            1, 0, bean.remark1.equals("1") ? 1 : 0, 0, 0, 0, 0, "", "", 0, maxTitleId, "0", 0, "",
                            DateUtil.formatDateTime(new Date()), 0, 0,
                            1, "完成任务", "g_88", "", 0, 0,
                            0, bean.url, "", 0, 0, 0, 0, "","0","0", bean.remark1.equals("1") ? "" : bean.id+"");
                    Toast.makeText(RecommendActivity.this, "已添加", Toast.LENGTH_SHORT).show();
                    sendBroadcast(intent);
                    break;
                case R.id.open:
                    dialog.dismiss();
                    Intent x = new Intent(RecommendActivity.this, WebViewActivity.class);
                    x.putExtra("url",bean.url);
                    x.putExtra("remark2",bean.id+"");
                    startActivity(x);
                    break;
                case R.id.cancle_tv:
                    dialog.dismiss();
                    break;
            }
        }
    }
}
